document.addEventListener('DOMContentLoaded', function() {
    // 使用Intersection Observer实现懒加载
    if('IntersectionObserver' in window) {
        const lazyImages = document.querySelectorAll('[data-src]');
        
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if(entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                    observer.unobserve(img);
                }
            });
        }, {
            rootMargin: '0px 0px 100px 0px'
        });
        
        lazyImages.forEach(img => {
            imageObserver.observe(img);
        });
    } else {
        // 不支持IntersectionObserver的备用方案
        const lazyLoadImages = function() {
            const lazyImages = document.querySelectorAll('[data-src]');
            lazyImages.forEach(img => {
                if(img.getBoundingClientRect().top <= window.innerHeight + 100 && 
                   img.getBoundingClientRect().bottom >= 0 && 
                   getComputedStyle(img).display !== 'none') {
                    img.src = img.dataset.src;
                    img.removeAttribute('data-src');
                }
            });
            
            if(document.querySelectorAll('[data-src]').length === 0) {
                document.removeEventListener('scroll', lazyLoadImages);
                window.removeEventListener('resize', lazyLoadImages);
                window.removeEventListener('orientationchange', lazyLoadImages);
            }
        };
        
        document.addEventListener('scroll', lazyLoadImages);
        window.addEventListener('resize', lazyLoadImages);
        window.addEventListener('orientationchange', lazyLoadImages);
        lazyLoadImages();
    }
    
    // 延迟加载非关键CSS
    const loadDeferredStyles = function() {
        const links = document.querySelectorAll('link[rel="stylesheet"][media="print"]');
        links.forEach(link => {
            link.media = 'all';
        });
    };
    
    if(window.requestIdleCallback) {
        window.requestIdleCallback(loadDeferredStyles);
    } else {
        window.addEventListener('load', loadDeferredStyles);
    }
});